import 'package:flutter/material.dart';

import '../../widgets/tags/divider.dart';
import '../../application.dart';
import '../../utils/tools.dart';
import '../../widgets/tags/empty.dart';
import '../../models/category_model.dart';
import '../../models/product_model.dart';
import '../../models/search_arguments.dart';
import '../../utils/api.dart';

class ListPage extends StatefulWidget {

  final SearchArguments arguments;

  const ListPage({Key key, this.arguments}) : super(key: key);

  @override
  _ListPageState createState() => _ListPageState();
}

class _ListPageState extends State<ListPage>  with SingleTickerProviderStateMixin {
  String _title = "产品";
  int topId = 0;
  int cateId = 0;

  int page = 1;
  int pageSize = 10;
  int total = 0;

  List<CategoryModel> _cates;
  List<ProductModel> _list;
  bool isLoading = true;
  bool isInitialize = false;
  bool hasMore = true;

  ScrollController _scrollController;
  TabController _tabController;

  @override
  void initState() {
    super.initState();
    
    var arguments = widget.arguments;
    if (arguments.category != null) {
      this.topId = arguments.category;
    }
    _scrollController = ScrollController();
    _scrollController.addListener(_onScroll);
    _list = List();
    _loadCategory();
  }

  _onScroll() {
    if (!isLoading) {
      //print(_scrollController.position);
      if (hasMore &&
          _scrollController.position.pixels + 10 >=
              _scrollController.position.maxScrollExtent) {
        setState(() {
          isLoading = true;
        });
        page++;
        _loadData();
      }
    }
  }

  _changeCate(int cateId) {
    setState(() {
      this.cateId = cateId;
    });
    _reloadData();
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(_title),
      ),
      body: isInitialize
          ? Column(
              children: <Widget>[
                (_cates == null || _cates.isEmpty)
                    ? SizedBox()
                    : TabBar(
                        onTap: (idx) {
                          cateId = _cates[idx].id;
                          _changeCate(cateId);
                        },
                        controller: _tabController,
                        tabs: _cates.map<Tab>((item) {
                          return Tab(
                            text: item.title,
                          );
                        }).toList(),
                      ),
                _renderList(),
              ],
            )
          : Center(
              child: CircularProgressIndicator(),
            ),
    );
  }

  _renderList() {
    if (_list == null || _list.isEmpty) {
      if (isLoading) {
        return Center(
          child: CircularProgressIndicator(),
        );
      }
      return TagEmpty('该类目暂无产品');
    }

    List<Widget> childs = _list.map<Widget>((prod) {
      return Card(
        child: ListTile(
          onTap: (){
            Application.route('/product/detail',arguments:{ 'id':prod.id ,'data':prod});
          },
          leading:(prod.image != null && prod.image.isNotEmpty)?Tools.image(prod.image,width:100,height:100):null,
          title: Text(prod.title),
          trailing: RaisedButton(onPressed: (){
            Application.route('/product/detail',arguments:{ 'id':prod.id ,'data':prod});
          },child: Text('查看详情'),),
        ),
      );
    }).toList();

    if (isLoading) {
      childs.add(Padding(
        padding: EdgeInsets.symmetric(vertical: 10),
        child: Center(
          child: SizedBox(
            height: 20,
            child: CircularProgressIndicator(
              strokeWidth: 2,
            ),
          ),
        ),
      ));
    } else if (!hasMore) {
      childs.add(TagDivider('没有更多了~'));
    }

    return Expanded(
      child: ListView(
        controller: _scrollController,
        children: childs,
      ),
    );
  }

  _loadCategory() async{
    Api.post('product/get_cates', {
      'pid': this.topId
    }).then((result) {
      var list = result.list;
      if (list != null) {
        
        setState(() {
          _cates = list.map((item) => CategoryModel.fromJson(item)).toList();
        
        int initIndex= 0;
          if(cateId == 0 || cateId==topId) {
            this.cateId = _cates[0].id;
          }else{
            initIndex = _cates.indexWhere( (item)=>item.id == cateId);
            if(initIndex < 0){
              initIndex = 0;
              cateId = _cates[0].id;
            }
          }
          _tabController = TabController( initialIndex:(initIndex<=0?0:initIndex),length:_cates.length, vsync: this);
        });
      } else {
        this.cateId = this.topId;
      }
      setState(() {
        isInitialize = true;
      });
      _loadData();
      
    });
  }

  _reloadData() {
    setState(() {
      page = 1;
      hasMore = true;
      isLoading = true;
      _list.clear();
    });
    _loadData();
  }

  _loadData() async{
    Api.post('product/get_list', {
      'cate': this.cateId,
      'page': this.page,
      'pagesize': this.pageSize
    }).then((result) {
      if(!mounted)return;
      var lists = result.data['lists'];
      setState(() {
        isLoading = false;
        total = Tools.parseInt(result.data['total']);
        if (lists != null) {
          _list += lists.map<ProductModel>((item) => ProductModel.fromJson(item)).toList();
        }
        if (lists == null || lists.length < pageSize || _list.length >= total) {
          hasMore = false;
        }
      });
    }).catchError((err) {
      setState(() {
        isLoading = false;
      });
    });
  }
}
